﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using Cookbook.Common;
using Cookbook.Services.Core.Domain;
using Cookbook.Services.Core.ExceptionHandling;

namespace Cookbook.Services.Core.Persistency.Common
{
    public abstract class Repository<T> : IQueryable<T> where T : class, IEntity
    {
        protected abstract IQueryable<T> Entities { get; }

        public Type ElementType
        {
            get { return Entities.ElementType; }
        }

        public Expression Expression
        {
            get { return Entities.Expression; }
        }

        public IQueryProvider Provider
        {
            get { return Entities.Provider; }
        }

        public T Get(object id)
        {
            var entity = Entities.SingleOrDefault(e => e.Id.Equals(id));

            if (entity == null)
            {
                throw new ApplicationErrorException(ServiceError.RecordDoesNotExistAnymore)
                {
                    { "Entity",  typeof(T).Name}
                };
            }

            return entity;
        }

        public void AddRange(IEnumerable<T> entities)
        {
            foreach (var entity in entities)
            {
                Add(entity);
            }
        }

        public void RemoveRange(IEnumerable<T> entities)
        {
            foreach (var entity in entities)
            {
                Remove(entity);
            }
        }

        public abstract void Add(T entity);
        public abstract void Remove(T entity);

        public IEnumerator<T> GetEnumerator()
        {
            return Entities.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return Entities.GetEnumerator();
        }
    }
}